<?php
/**
 * This controller using for process any ajax request
 */
class AjaxController extends AppController {
	var $uses = array();

	function beforeFilter() {
		parent::beforeFilter();
		$this->CustomAuth->allow('course_detail', 'addWatchList');
		if (!$this->RequestHandler->isAjax()) {
			$this->cakeError('error404');
		}
	}

	/**
	 * Update course schedule when change the course detail on the select box
	 *
	 * @return string The html data
	 */
	function course_detail() {
		$detailId = 0;
		if (isset($this->params['url']['detail'])) {
			$detailId = $this->params['url']['detail'];
		}
		$this->loadModel('CourseDetail');
		$detail = $this->CourseDetail->getCourseDetail($detailId);
		if ($detail) {
			//check if user entered course
			$userId = $this->CustomAuth->user('id');
			$this->loadModel('EnteredCourse');
			$isJoined = false;
			if ($detail) {
				$isJoined = $this->EnteredCourse->isEnteredCourse($detail['CourseDetail']['id'], $userId);
			}

			//set need value for course of detail
			$course['Course']['id'] = $detail['CourseDetail']['course_id'];
			$course['Course']['title'] = $detail['Course']['title'];
			$this->set(array(
				'detail' => $detail,
				'course' => $course,
				'detailId' => $detailId,
				'isJoined' => $isJoined,
				'isOwner' => $this->CourseDetail->isOwner($detailId, $userId),
				'isFull' => $this->CourseDetail->isFull($detailId),
			));
		}
		return $this->render('/elements/course/schedule', 'ajax');
	}
	
	function addWatchList() {
		$userId = $this->CustomAuth->user('id');
		//if user not yet to login
		if(!$userId){
			$url = Router::url(array('controller' => 'Users', 'action' => 'signin'));
			$this->set(array(
				'url' => $url
			));
			//redirect url after login
			$this->Session->write('Auth.redirect', $this->referer());
			return $this->render('/elements/blank_page', 'ajax');
		}else{// user logined, insert to database
			$teacherId = '';
			$this->loadModel('TargetOfWatch');
			if(isset($this->params['url']['data_id'])){
				$teacherId = $this->params['url']['data_id'];
			}
			$isExistWatchList = $this->TargetOfWatch->isExistsRecord($userId, $teacherId);
			$isOwner = ($userId == $teacherId) ? true : false;
			if($isExistWatchList == false){
				//insert database
				$targetOfWatch = array(
					'user_id' => $userId,
					'watch_id' => $teacherId
				);
				$watchListInfo = $this->TargetOfWatch->saveData($targetOfWatch);
				if(is_array($watchListInfo)){
					$watchListInfo[$this->TargetOfWatch->alias]['id'] = $this->TargetOfWatch->id;
					$this->set(array(
						'watchListInfo' => $watchListInfo
					));
				}
			}
			$this->set(array(
				'teacherId' => $teacherId,
				'userId' => $userId,
				'isOwner' => $isOwner

			));
			return $this->render('/elements/watch_section', 'ajax');
		}
	}
	
	function removeWatchList(){
		$userId = $this->CustomAuth->user('id');
		//if user not yet to login
		if(!$userId){
			$url = Router::url(array('controller' => 'Users', 'action' => 'signin'));
			$this->set(array(
				'url' => $url
			));
			//redirect url after login
			$this->Session->write('Auth.redirect', $this->referer());
			return $this->render('/elements/blank_page', 'ajax');
		}else{// user logined, remove data
			$teacherId = '';
			$watchListId = '';
			$this->loadModel('TargetOfWatch');
			if(isset($this->params['url']['data_id'])){
				$teacherId = $this->params['url']['data_id'];
			}
			if(isset($this->params['url']['watchlist_id'])){
				$watchListId = $this->params['url']['watchlist_id'];
			}
			$this->TargetOfWatch->deleteData($watchListId, $this->CustomAuth->user('id'));
			$watchListInfo = $this->TargetOfWatch->getTargetOfWatchInformationByUserIdAndTeacherId($userId, $teacherId);
			$isOwner = ($userId == $teacherId) ? true : false;
			$this->set(array(
				'teacherId' => $teacherId,
				'watchListInfo' => $watchListInfo,
				'userId' => $userId,
				'isOwner' => $isOwner

			));
			return $this->render('/elements/watch_section', 'ajax');
		}
	}

	function user_status() {
		return $this->render('/elements/course_pending', 'ajax');
	}

	function admin_schedule() {
		if(isset($this->params['url']['start'])) {
			$start = date('Y-m-d H:i:s', $this->params['url']['start']);
		}
		if(isset($this->params['url']['end'])) {
			$end = date('Y-m-d H:i:s', $this->params['url']['end']);
		}
		$this->loadModel('CourseDetail');
		$json = array();
		if(isset($this->params['url']['all']) && $this->params['url']['all'] == 1) {
			$showAll = true;
		} else {
			$showAll = false;
		}
		if(isset($start) && isset($end)) {
			if($showAll == true) {
				$courseDetails = $this->CourseDetail->getCourseDetailInDuration($start, $end, NULL);
			} else {
				$courseDetails = $this->CourseDetail->getCourseDetailInDuration($start, $end, CourseDetail::CALENDAR_COURSE_LIMIT);
			}
			$total = $this->CourseDetail->countCourseDetailInDuration($start, $end);
			if($total <= CourseDetail::CALENDAR_COURSE_LIMIT) {
				$readMore = 0;
			} else {
				$readMore = 1;
			}
			if($showAll == false) {
				$time = 0;
				foreach ($courseDetails as $key => $courseDetail) {
					if ($time < strtotime($courseDetail['CourseDetail']['closing_date'])) {
						$time = strtotime($courseDetail['CourseDetail']['closing_date']);
					}
					$data = array(
						'title' => $courseDetail['Course']['title'] . ' - ' . date('H:i', strtotime($courseDetail['CourseDetail']['opening_date'])) ,
						'start' => $courseDetail['CourseDetail']['opening_date'],
						'end' => $courseDetail['CourseDetail']['closing_date'],
						'url' => Router::url(array('controller' => 'course', 'action' => 'view', $courseDetail['Course']['id'], 'admin' => false))
					);
					array_push($json, $data);
				}
				if($readMore == 1) {
					$data = array(
						'title' => Messages::read_more,
						'start' => date('Y-m-d H:i:s', $time),
						'end' => date('Y-m-d H:i:s', $time + 84600),
						'readmore' => $readMore,
						'start_params' => $this->params['url']['start'],
						'end_params' => $this->params['url']['end'],
					);
				}
				$this->set('json', $json);

				return $this->render('/elements/json', 'ajax');
			} else {
				$this->set('courseDetails', $courseDetails);
				return $this->render('/elements/schedule_html', 'ajax');
			}
			
		}
	}
}